package com.zxc.controller.wechat;

/*
 * 编写5个类，来获取关注此公众号的用户信息
 *
 * WechatLoginController、UserAccessToken、WechatUser、WechatUtil、MyX666TrustManager
 * */

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zxc.common.dto.WechatAuthExecution;
import com.zxc.common.enums.wechat.WechatAuthStateEnum;
import com.zxc.common.lang.Result;
import com.zxc.entity.wechat.PersonInfo;
import com.zxc.entity.wechat.WechatAuth;
import com.zxc.service.wechat.WechatAuthService;
import com.zxc.util.DesUtil;
import com.zxc.util.JwtUtils;
import com.zxc.util.wechat.WechatUserUtil;
import com.zxc.util.wechat.message.pojo.UserAccessToken;
import com.zxc.util.wechat.message.pojo.WechatUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//用来获取已关注此微信号的用户信息并做相应的处理
//关注公众号之后的微信用户信息接口，如果在微信浏览器里访问
//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb48db798b844ceda&redirect_uri=http://zxcservice.xyz/o2o/wechatlogin/logincheck&role_type=1&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect
//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx34f2f337ff46f766&redirect_uri=http://47.96.236.61/wechatlogin/logincheck&role_type=P0AD3Nh0egM=&response_type=code&scope=snsapi_userinfo&state=wechat#wechat_redirect

@Controller
@RequestMapping(value = "wechatlogin")
public class WechatLoginController {

    @Autowired
    private WechatAuthService wechatAuthService;
    @Autowired
    private JwtUtils jwtUtils;

    @RequestMapping(value = "/logincheck", method = RequestMethod.GET)
    public Result doGet(HttpServletRequest request, HttpServletResponse response) {
        //获取微信公众号传输过来的code，通过code可获取access_token,进而获取用户信息
        String code = request.getParameter("code");

        //这个state可以用来传输我们自定义的信息，方便程序调试，这里也可以不用
        //判断当前的角色类型是啥，有两个按钮，一个是前端展示系统，一个是店家管理页面
        String roleType = request.getParameter("state");

        WechatUser user = null;
        String openId = null;
        WechatAuth wechatAuth = null;
        if (null != code) {
            UserAccessToken token;

            try {
                //通过code获取access_token
                token = WechatUserUtil.getUserAccessToken(code);
                if (ObjectUtils.isNotEmpty(token)) {
                    //通过token获取accessToken
                    String accessToken = token.getAccessToken();

                    System.out.println("通过token获取accessToken=" + accessToken);

                    //通过token获取openId
                    openId = token.getOpenId();

                    //通过access_token和openId获取用户昵称等信息
                    user = WechatUserUtil.getUserInfo(accessToken, openId);

                    System.out.println("用户信息===========" + user);

                    request.getSession().setAttribute("openId", DesUtil.getEncryptMessageStr(openId));
                    wechatAuth = wechatAuthService.findWechatAuthByOpenId(openId);

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // === to do begin ===
        //前面获取到openId之后，可以通过它去数据库判断该微信账号是否在我们网站里有对应的账号了，没有的话这里可以自动创建上，直接实现
        //微信与我们的网站的无缝对接,首次登录
        // === to do end ===
        if (wechatAuth == null && ObjectUtils.isNotEmpty(user)) {
            //从微信返回的信息里面提取提取数据库需要的字段信息
            PersonInfo personInfo = WechatUserUtil.getPersonInfoFromRequest(user);
            wechatAuth = new WechatAuth();
            wechatAuth.setPersonInfo(personInfo);
            wechatAuth.setOpenId(openId);
            //注册信息
            WechatAuthExecution wechatAuthExecution = wechatAuthService.register(wechatAuth);
            if (WechatAuthStateEnum.SUCCESS.getState().equals(wechatAuthExecution.getState())) {
                //注册/登录成功，用户自动登录
                //根据openId查询用户信息
                PersonInfo person = wechatAuthService.getOne(new QueryWrapper<PersonInfo>().eq("open_id", wechatAuth.getOpenId()));
                System.out.println("数据库存储用户信息=" + person);
                String jwt = jwtUtils.generateToken(person.getOpenId());
                response.setHeader("Authorization", jwt);
                response.setHeader("Access-control-Expose-Headers", "Authorization");
                //登录类型
                response.setHeader("state", "wechat");
                return Result.succ(MapUtil.builder()
                        .put("id", personInfo.getOpenId())
                        .put("username", personInfo.getName())
                        .put("avatar", personInfo.getProfileImg())
                        .put("email", personInfo.getEmail())
                        .map()
                );
            } else {
                //注册失败。
            }
        }
        return null;

    }
}
